<template>
  <div class="z-load-img-to-base64">
    <!-- 展示图片 -->
    <img v-if="base64Image" :src="base64Image" alt="Base64 Image" />
    <span v-else-if="loading"><LoadingIcon width="26" /></span>
    <span v-else-if="error"><ImgError width="26" /></span>
    <span v-else></span>
  </div>
</template>

<script>
import axios from 'axios' // 引入 axios
import LoadingIcon from './components/LoadingIcon.vue'
import ImgError from './components/ImgError.vue'

export default {
  name: 'ZLoadImgToBase64',
  components: { LoadingIcon, ImgError },
  props: {
    imgUrl: { type: String, default: '' },
  },
  watch: {
    imgUrl: {
      handler(newUrl) {
        if (!newUrl) return this.resetState()
        this.convertImageToBase64(newUrl)
      },
      immediate: true,
    },
  },
  data() {
    return {
      base64Image: '', // 用于存储 Base64 图片数据
      loading: true, // 加载状态
      error: '', // 错误信息
    }
  },
  methods: {
    // 将图片地址转换为 Base64
    async convertImageToBase64(url) {
      this.resetState() // 重置状态
      this.loading = true // 开始加载
      try {
        if (url.includes('base64')) {
          this.base64Image = url
        } else {
          // 使用 axios 获取图片的 Blob 对象并直接转换为 Base64
          const response = await axios.get(url, { responseType: 'blob' })
          const blob = response.data
          this.base64Image = await this.blobToBase64(blob)
          // this.error = 'Failed'
        }
      } catch (error) {
        this.error = 'Failed'
        console.error(`Error converting image to Base64 for URL: ${url}`, error)
      } finally {
        this.loading = false // 结束加载
      }
    },
    // 工具函数：将 Blob 转换为 Base64
    blobToBase64(blob) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result) // 读取为 Base64
        reader.onerror = reject
        reader.readAsDataURL(blob) // 将 Blob 转换为 Data URL
      })
    },
    // 重置组件状态
    resetState() {
      this.base64Image = ''
      this.loading = false
      this.error = ''
    },
  },
}
</script>

<style scoped lang="scss">
.z-load-img-to-base64 {
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 100%;
    height: auto;
    border-radius: 8px;
    display: block;
    margin: 0 auto; /* 居中显示 */
  }
}
</style>
